package com.thirdgroup.listener;

import com.thirdgroup.service.SchedulerService;
import com.thirdgroup.service.impl.SchedulerServiceImpl;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
@WebListener
public class SchedulerContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        Timer timer = new Timer();
        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为每个月的第一天
//        calendar.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为0
//        calendar.set(Calendar.MINUTE, 49); // 设置分钟为0
//        calendar.set(Calendar.SECOND, 0); // 设置秒数为0
//        Date firstDayOfMonth = calendar.getTime();
        calendar.setTime(new Date());
        calendar.add(calendar.MINUTE,1);
        Date firstDayOfMonth = calendar.getTime();

        // 每个月的第一天0时触发任务
        timer.schedule(new SchedulerTask(), firstDayOfMonth);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // 在Web应用程序关闭时执行一些清理操作
    }

    private static class SchedulerTask extends TimerTask {
        @Override
        public void run() {
            // 在这里调用自动处理方法
//            SchedulerService schedulerService = new SchedulerServiceImpl();
//            schedulerService.automatic();
        }
    }
}
